package com.hanserwei.community.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hanserwei.community.entity.po.House;
import com.hanserwei.community.entity.po.Owner;
import com.hanserwei.community.entity.request.OwnerQueryRequest;
import com.hanserwei.community.entity.vo.HouseVO;
import com.hanserwei.community.entity.vo.OwnerVO;
import com.hanserwei.community.enums.ResponseCodeEnum;
import com.hanserwei.community.mapper.OwnerMapper;
import com.hanserwei.community.service.HouseService;
import com.hanserwei.community.service.OwnerService;
import com.hanserwei.community.uitils.ThrowUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class OwnerServiceImpl extends ServiceImpl<OwnerMapper, Owner> implements OwnerService {
    private final HouseService houseService;

    @Override
    public boolean saveOwner(Owner owner) {
        ThrowUtils.throwIf(owner == null, ResponseCodeEnum.INVALID_PARAMETER, "业主信息不能为空！");
        validateOwnerRelations(owner);
        boolean result = save(owner);
        ThrowUtils.throwIf(!result, ResponseCodeEnum.SYSTEM_ERROR, "添加失败！");
        return true;
    }

    @Override
    public boolean updateOwner(Owner owner) {
        ThrowUtils.throwIf(owner == null, ResponseCodeEnum.INVALID_PARAMETER, "业主信息不能为空！");
        ThrowUtils.throwIf(owner.getId() == null || owner.getId() <= 0, ResponseCodeEnum.INVALID_PARAMETER, "业主ID参数错误！");
        Owner dbOwner = getById(owner.getId());
        ThrowUtils.throwIf(dbOwner == null, ResponseCodeEnum.RESOURCE_NOT_FOUND, "业主不存在！");
        validateOwnerRelations(owner);
        boolean result = updateById(owner);
        ThrowUtils.throwIf(!result, ResponseCodeEnum.SYSTEM_ERROR, "更新失败！");
        return true;
    }

    @Override
    public Page<OwnerVO> listByPage(OwnerQueryRequest request) {
        Page<Owner> page = new Page<>(request.getCurrent(), request.getPageSize());
        QueryWrapper<Owner> queryWrapper = getQueryWrapper(request);
        Page<Owner> ownerPage = page(page, queryWrapper);
        List<Owner> ownerList = ownerPage.getRecords();
        List<OwnerVO> ownerVOList = getOwnerVOList(ownerList);
        Page<OwnerVO> ownerVOListPage = new Page<>(ownerPage.getCurrent(), ownerPage.getSize(), ownerPage.getTotal());
        ownerVOListPage.setRecords(ownerVOList);
        return ownerVOListPage;
    }


    @Override
    public QueryWrapper<Owner> getQueryWrapper(OwnerQueryRequest request) {
        QueryWrapper<Owner> queryWrapper = new QueryWrapper<>();
        if (request != null) {
            queryWrapper.eq(request.getId() != null && request.getId() > 0, "id", request.getId());
            queryWrapper.like(request.getUserName() != null && !request.getUserName().isEmpty(), "user_name", request.getUserName());
            queryWrapper.eq(request.getTel() != null && !request.getTel().isEmpty(), "tel", request.getTel());
            queryWrapper.eq(request.getSex() != null && !request.getSex().isEmpty(), "sex", request.getSex());
            queryWrapper.eq(request.getIdentity() != null && !request.getIdentity().isEmpty(), "identity", request.getIdentity());
            queryWrapper.like(request.getRemarks() != null && !request.getRemarks().isEmpty(), "remarks", request.getRemarks());
            queryWrapper.eq(request.getHouseId() != null && request.getHouseId() > 0, "house_id", request.getHouseId());
            if (request.getBuildingId() != null && request.getBuildingId() > 0) {
                List<Integer> houseIds = houseService.lambdaQuery()
                        .select(House::getId)
                        .eq(House::getBuildingId, request.getBuildingId())
                        .list()
                        .stream()
                        .map(House::getId)
                        .toList();
                if (houseIds.isEmpty()) {
                    queryWrapper.apply("1 = 0");
                } else {
                    queryWrapper.in("house_id", houseIds);
                }
            }
        }
        return queryWrapper;
    }

    /**
     * 获取OwnerVO
     * @param owner owner
     * @return OwnerVO
     */
    @Override
    public OwnerVO getOwnerVO(Owner owner){
        ThrowUtils.throwIf(owner == null, ResponseCodeEnum.INVALID_PARAMETER, "业主信息不能为空！");
        OwnerVO ownerVO = new OwnerVO();
        BeanUtils.copyProperties(owner, ownerVO);
        ownerVO.setHouseId(owner.getHouseId());
        if (owner.getHouseId() != null) {
            House house = houseService.getById(owner.getHouseId());
            if (house != null) {
                ownerVO.setHouseVO(houseService.getHouseVO(house));
            }
        }
        return ownerVO;
    }

    @Override
    public OwnerVO getOwnerVOById(Integer ownerId) {
        ThrowUtils.throwIf(ownerId == null || ownerId <= 0, ResponseCodeEnum.INVALID_PARAMETER, "业主ID参数错误！");
        Owner owner = getById(ownerId);
        ThrowUtils.throwIf(owner == null, ResponseCodeEnum.RESOURCE_NOT_FOUND, "业主不存在！");
        return getOwnerVO(owner);
    }

    /**
     * 获取OwnerVO列表
     * @param ownerList ownerList
     * @return OwnerVOList
     */
    @Override
    public List<OwnerVO> getOwnerVOList(List<Owner> ownerList){
        if (ownerList == null || ownerList.isEmpty()) {
            return Collections.emptyList();
        }

        List<Integer> houseIds = ownerList.stream()
                .map(Owner::getHouseId)
                .filter(Objects::nonNull)
                .distinct()
                .toList();

        final Map<Integer, HouseVO> houseVOMap;
        if (!houseIds.isEmpty()) {
            List<House> houseList = houseService.listByIds(houseIds);
            List<HouseVO> houseVOList = houseService.getHouseVOList(houseList);
            houseVOMap = houseVOList.stream()
                    .collect(Collectors.toMap(HouseVO::getId, houseVO -> houseVO));
        } else {
            houseVOMap = Collections.emptyMap();
        }

        return ownerList.stream().map(owner -> {
            OwnerVO ownerVO = new OwnerVO();
            BeanUtils.copyProperties(owner, ownerVO);
            ownerVO.setHouseId(owner.getHouseId());
            if (owner.getHouseId() != null) {
                ownerVO.setHouseVO(houseVOMap.get(owner.getHouseId()));
            }
            return ownerVO;
        }).toList();
    }

    private void validateOwnerRelations(Owner owner) {
        ThrowUtils.throwIf(owner.getUserName() == null || owner.getUserName().isEmpty(), ResponseCodeEnum.INVALID_PARAMETER, "业主姓名不能为空！");
        ThrowUtils.throwIf(owner.getTel() == null || owner.getTel().isEmpty(), ResponseCodeEnum.INVALID_PARAMETER, "联系电话不能为空！");
        ThrowUtils.throwIf(owner.getHouseId() == null || owner.getHouseId() <= 0, ResponseCodeEnum.INVALID_PARAMETER, "请选择关联房屋！");

        Long telCount = lambdaQuery()
                .eq(Owner::getTel, owner.getTel())
                .ne(owner.getId() != null && owner.getId() > 0, Owner::getId, owner.getId())
                .count();
        ThrowUtils.throwIf(telCount != null && telCount > 0, ResponseCodeEnum.INVALID_PARAMETER, "联系电话已存在！");

        House house = houseService.getById(owner.getHouseId());
        ThrowUtils.throwIf(house == null, ResponseCodeEnum.INVALID_PARAMETER, "关联房屋不存在！");

        Long occupiedCount = lambdaQuery()
                .eq(Owner::getHouseId, owner.getHouseId())
                .ne(owner.getId() != null && owner.getId() > 0, Owner::getId, owner.getId())
                .count();
        ThrowUtils.throwIf(occupiedCount != null && occupiedCount > 0, ResponseCodeEnum.INVALID_PARAMETER, "该房屋已绑定其他业主，不能重复分配！");
    }
}
